Shader "Custom/ActivatedWireframesLifecycle_GlitchNoise" // 新名称，反映噪声类型
{
    Properties
    {
        // --- Lifecycle & Color ---
        _UpdateRate ("Update Rate (Hz)", Range(0.1, 20.0)) = 3.0
        _Intensity ("Intensity", Range(0.5, 5.0)) = 1.5
        _ColorRed ("Red Color", Color) = (1,0.2,0.2,1)
        _ColorGreen ("Green Color", Color) = (0.2,0.9,0.3,1)
        _ColorPurple ("Purple Color", Color) = (0.8,0.2,0.9,1)

        // --- Rectangle Generation ---
        _GridDensity ("Grid Density", Range(5, 100)) = 30
        _MinRectSize ("Min Rect Size", Range(0.1, 3.0)) = 0.8
        _MaxRectSize ("Max Rect Size", Range(0.5, 8.0)) = 3.5
        _AspectRatioRange ("Aspect Ratio Range", Range(1.0, 5.0)) = 2.0

        // --- Activation & Flow (使用旧代码片段中的噪声参数名) ---
        _ActivationThreshold ("Activation Threshold", Range(0.1, 0.9)) = 0.6 // 对应旧的 _NoiseThreshold
        _ActivationNoiseScale ("Activation Noise Scale", Range(0.5, 30.0)) = 5.0 // 对应旧的 _NoiseScale
        _Speed ("Flow Speed", Range(0.0, 5.0)) = 0.5
        _FlowDirection ("Flow Direction (XY)", Vector) = (0,1,0,0) // Default flow up

        // --- Wireframe ---
        _WireframeThickness ("Wireframe Thickness", Range(0.01, 0.5)) = 0.08 // Relative to grid cell size
        _ShapeVariety ("Shape Variety", Range(0, 1)) = 0.8
        _InnerDetail ("Inner Detail", Range(0, 1)) = 0.5
    }

    SubShader
    {
        Tags {
            "RenderType" = "Opaque"
            "RenderPipeline" = "UniversalPipeline"
            "Queue" = "Geometry"
        }

        Pass
        {
            HLSLPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"

            struct Attributes
            {
                float4 positionOS : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct Varyings
            {
                float4 positionCS : SV_POSITION;
                float2 uv : TEXCOORD0;
            };

            CBUFFER_START(UnityPerMaterial)
                // Lifecycle & Color
                float _UpdateRate;
                float _Intensity;
                float4 _ColorRed;
                float4 _ColorGreen;
                float4 _ColorPurple;
                // Rectangle Generation
                float _GridDensity;
                float _MinRectSize;
                float _MaxRectSize;
                float _AspectRatioRange;
                // Activation & Flow
                float _ActivationThreshold;
                float _ActivationNoiseScale;
                float _Speed;
                float4 _FlowDirection;
                // Wireframe
                float _WireframeThickness;
                float _ShapeVariety;
                float _InnerDetail;
            CBUFFER_END

            // Hash function
            float hash21(float2 p)
            {
                p = frac(p * float2(123.34, 456.21));
                p += dot(p, p + 45.32);
                return frac(p.x * p.y);
            }

            // Noise functions (Value Noise + FBM)
            float valueNoise2D(float2 uv)
            {
                float2 i = floor(uv);
                float2 f = frac(uv);
                float a = hash21(i);
                float b = hash21(i + float2(1, 0));
                float c = hash21(i + float2(0, 1));
                float d = hash21(i + float2(1, 1));
                float2 u = f * f * (3.0 - 2.0 * f);
                return lerp(lerp(a, b, u.x), lerp(c, d, u.x), u.y);
            }

            float fbmValueNoise(float2 uv)
            {
                float sum = 0.0;
                float amp = 0.5;
                float freq = 1.0;
                for (int i = 0; i < 4; i++) // 4 octaves
                {
                    sum += valueNoise2D(uv * freq) * amp;
                    freq *= 2.0;
                    amp *= 0.5;
                }
                return sum;
            }

            float calculateActivatedWireframes(float2 uv, float time)
            {
                float quantizedTime = floor(time * _UpdateRate) / _UpdateRate;
                float2 cellID = floor(uv * _GridDensity);
                float finalWireValue = 0.0;
                int overlapCount = 0;
                
                float2 flowDir = normalize(_FlowDirection.xy);
                if (length(flowDir) < 0.01) flowDir = float2(0, 1); // Default flow up
                float timeOffset = quantizedTime * _Speed;
                
                // 增大周围检查区域，确保宽形状不会被裁剪
                // 检查5x3网格区域 (左右多检查，上下少检查)
                for (int j = -1; j <= 1; j++) 
                {
                    for (int i = -2; i <= 2; i++) // 水平方向检查范围更大
                    {
                        float2 neighborCellID = cellID + float2(i, j);
                        
                        float2 activationBaseUV = neighborCellID / _GridDensity;
                        float2 noiseUV = (activationBaseUV - flowDir * timeOffset) * _ActivationNoiseScale;
                        float noiseValue = fbmValueNoise(noiseUV);
                        noiseValue = abs(frac(noiseValue * 3.0 + quantizedTime * 0.7) - 0.5) * 2.0;
                        float activationSignal = step(_ActivationThreshold, noiseValue);
                        
                        if (activationSignal > 0.5)
                        {
                            // 生成形状参数
                            float seed = hash21(neighborCellID + floor(quantizedTime * 0.7));
                            float hash1 = hash21(neighborCellID + seed + 1.1);
                            float hash2 = hash21(neighborCellID + seed + 2.2);
                            float hash3 = hash21(neighborCellID + seed + 3.3);
                            float hash4 = hash21(neighborCellID + seed + 4.4);
                            float hash5 = hash21(neighborCellID + seed + 5.5);
                            float hash6 = hash21(neighborCellID + seed + 6.6);
                            float hash7 = hash21(neighborCellID + seed + 7.7);
                            
                            // 形状类型决定（基于_ShapeVariety和随机值）
                            float shapeTypeRand = hash5 * _ShapeVariety;
                            int shapeType = floor(shapeTypeRand * 3.999); // 仅使用封闭形状 (0-3)
                            
                            float2 rectCenterOffset = (float2(hash1, hash2) * 2.0 - 1.0) * 0.3;
                            float2 rectCenter = (neighborCellID + 0.5 + rectCenterOffset) / _GridDensity;
                            
                            float rectBaseSize = lerp(_MinRectSize, _MaxRectSize, hash3);
                            
                            // 改进宽高比生成
                            float aspectRatio;
                            
                            // 70%的概率生成宽形状，30%的概率生成高形状或正方形
                            if (hash6 < 0.7) {
                                // 宽形状: 使用幂函数分布，生成更多更宽的形状
                                aspectRatio = pow(hash4, 0.7) * (_AspectRatioRange * 1.5) + 1.0;
                            } else {
                                // 高形状或正方形: 更温和的纵横比
                                if (hash6 < 0.85) {
                                    // 高形状
                                    aspectRatio = 1.0 / (lerp(1.0, _AspectRatioRange * 0.8, hash4));
                                } else {
                                    // 接近正方形的形状
                                    aspectRatio = lerp(0.9, 1.1, hash4);
                                }
                            }
                            
                            float rectHalfWidth = rectBaseSize * aspectRatio * 0.5 / _GridDensity;
                            float rectHalfHeight = rectBaseSize / aspectRatio * 0.5 / _GridDensity;
                            
                            // --- 生成封闭形状 ---
                            float2 relPos = uv - rectCenter;
                            float distToEdge;
                            
                            if (shapeType == 0) {
                                // 标准矩形
                                float2 d = abs(relPos) - float2(rectHalfWidth, rectHalfHeight);
                                float outside = length(max(d, 0.0));
                                float inside = min(max(d.x, d.y), 0.0);
                                distToEdge = outside + inside;
                            }
                            else if (shapeType == 1) {
                                // 圆角矩形
                                float cornerRadius = min(rectHalfWidth, rectHalfHeight) * lerp(0.1, 0.5, hash4);
                                float2 d = abs(relPos) - float2(rectHalfWidth - cornerRadius, rectHalfHeight - cornerRadius);
                                float outside = length(max(d, 0.0)) - cornerRadius;
                                float inside = min(max(d.x, d.y), 0.0);
                                distToEdge = outside + inside;
                            }
                            else if (shapeType == 2) {
                                // 八边形
                                float2 absPos = abs(relPos);
                                float angle = (hash7 < 0.5) ? 0.0 : 0.125; // 可以旋转45度
                                float r = 1.082; // 归一化因子
                                float2 d = abs(absPos * cos(angle) + absPos.yx * sin(angle));
                                float octDist = max(d.x / rectHalfWidth, d.y / rectHalfHeight) * r;
                                distToEdge = (octDist - 1.0) * min(rectHalfWidth, rectHalfHeight);
                            }
                            else { // shapeType == 3
                                // 圆形/椭圆
                                float2 scaled = relPos / float2(rectHalfWidth, rectHalfHeight);
                                distToEdge = (length(scaled) - 1.0) * min(rectHalfWidth, rectHalfHeight);
                            }
                            
                            // 判断是否在形状内部
                            bool isInside = distToEdge < 0;
                            if (isInside) overlapCount += 1;
                            
                            // 添加内部细节
                            float innerWire = 0.0;
                            if (_InnerDetail > 0.01 && isInside) {
                                float2 normPos;
                                if (shapeType == 3) {
                                    // 圆形内部细节需要特别处理
                                    normPos = relPos / float2(rectHalfWidth, rectHalfHeight);
                                } else {
                                    // 其他形状
                                    normPos = (relPos / float2(rectHalfWidth * 2.0, rectHalfHeight * 2.0)) + 0.5;
                                }
                                
                                if (hash6 < 0.5) {
                                    // 网格线
                                    float gridScale = lerp(1.0, 4.0, hash7);
                                    float2 gridPos = frac(normPos * gridScale);
                                    float gridDist = min(min(gridPos.x, 1.0 - gridPos.x), min(gridPos.y, 1.0 - gridPos.y));
                                    innerWire = smoothstep(0.05 * _InnerDetail, 0.04 * _InnerDetail, gridDist) * 0.5 * _InnerDetail;
                                } else {
                                    // 斜线
                                    float diagLine = min(abs(frac(normPos.x + normPos.y * aspectRatio + hash7) - 0.5),
                                                       abs(frac(normPos.x - normPos.y * aspectRatio + 0.5 + hash7) - 0.5));
                                    innerWire = smoothstep(0.06 * _InnerDetail, 0.04 * _InnerDetail, diagLine) * 0.5 * _InnerDetail;
                                }
                            }
                            
                            // 计算线框效果
                            float wireThicknessUV = _WireframeThickness / _GridDensity;
                            float mainWire = smoothstep(wireThicknessUV * 0.5, wireThicknessUV * 0.4, abs(distToEdge));
                            
                            // 应用断线效果
                            if (abs(distToEdge) < wireThicknessUV * 0.5 && hash7 > 0.7) {
                                float breakPattern = frac(dot(relPos, float2(12.9898, 78.233) * hash7) * 43758.5453);
                                if (breakPattern < 0.15) mainWire *= 0.3;
                            }
                            
                            float wire = max(mainWire, innerWire);
                            finalWireValue = max(finalWireValue, wire);
                        }
                    }
                }
                
                // 仍然处理重叠
                if (overlapCount > 1) return 0.0;
                return finalWireValue;
            }

            Varyings vert(Attributes IN)
            {
                Varyings OUT;
                OUT.positionCS = TransformObjectToHClip(IN.positionOS.xyz);
                OUT.uv = IN.uv;
                return OUT;
            }

            half4 frag(Varyings IN) : SV_Target
            {
                float2 uv = IN.uv;
                float time = _Time.y;

                float timeStepDuration = 1.0 / _UpdateRate;
                float quantizedTime_t0 = floor(time / timeStepDuration) * timeStepDuration;
                float quantizedTime_t1 = quantizedTime_t0 - timeStepDuration;
                float quantizedTime_t2 = quantizedTime_t0 - 2.0 * timeStepDuration;

                // 调用修改后的线框函数
                float wire_t0 = calculateActivatedWireframes(uv, quantizedTime_t0);
                float wire_t1 = calculateActivatedWireframes(uv, quantizedTime_t1);
                float wire_t2 = calculateActivatedWireframes(uv, quantizedTime_t2);

                float3 colorRed = _ColorRed.rgb;
                float3 colorGreen = _ColorGreen.rgb;
                float3 colorPurple = _ColorPurple.rgb;

                float3 finalColor = float3(0,0,0);

                // 颜色混合逻辑保持不变
                finalColor += wire_t2 * colorPurple;
                finalColor += wire_t1 * colorGreen;
                finalColor += wire_t0 * colorRed;

                finalColor *= _Intensity;

                return half4(finalColor, 1.0);
            }
            ENDHLSL
        }
    }
}